extends Area2D

var start_pos := Vector2.ZERO
var speed := 0

@onready var screensize = get_viewport_rect().size
@onready var shoot_timer: Timer = $ShootTimer
@onready var move_timer: Timer = $MoveTimer
@onready var animation_player: AnimationPlayer = $AnimationPlayer

var bullet_scene = preload("res://scene/enemy_bullet.tscn")

signal died

func start(pos)->void:
	speed = 0
	position = Vector2(pos.x, -pos.y)
	start_pos = pos
	#等待一个随机的时间
	await get_tree().create_timer(randf_range(0.25, 0.55)).timeout
	var tween = create_tween().set_trans(Tween.TRANS_BACK)
	tween.tween_property(self,"position:y",start_pos.y,1.4)
	await tween.finished
	move_timer.wait_time = randf_range(5,20)
	move_timer.start()
	shoot_timer.wait_time = randf_range(4,20)
	shoot_timer.start()
	add_to_group("enemies")
	
func explode():
	speed = 0
	animation_player.play("explode")
	set_deferred("monitoring",false)
	died.emit(5)
	await animation_player.animation_finished
	queue_free()

func _ready() -> void:
	pass 


func _process(delta: float) -> void:
	position.y += speed * delta
	if position.y > screensize.y + 32:
		start(start_pos)
	
	#if move_timer.time_left > 0 && shoot_timer.time_left==0: #还没有开始移动的时候是可以发射子弹的
		

func _on_move_timer_timeout() -> void:
	speed = randf_range(75, 100)


func _on_shoot_timer_timeout() -> void:
	var b:EnemyBullet = bullet_scene.instantiate()
	get_tree().root.add_child(b)
	b.start(position)
	shoot_timer.wait_time = randf_range(4,20)
	shoot_timer.start()
